<style lang="scss">
.sku_table .el-table table .cell {
	font-weight: 700;
	color: #909399;
	font-size: 12px;
}
.sku_table .el-table .cell {
	text-overflow: clip;
	white-space: nowrap;
	overflow: hidden;
	padding: 0 5px;
}
.cell .smini-input {
	width: 75px;
}
.smini-input.el-input-number.is-without-controls .el-input__inner {
	padding-left: 0;
	padding-right: 0;
}
.spec-photo {
	cursor: pointer;
}
</style>

<template>
	<div class="container sku_table">
		<el-dialog
			title="规格图片"
			width="665px"
			v-model="specImageVisible"
			:append-to-body="true"
			:close-on-click-modal="false"
		>
			<sc-upload-multiple ref="specImage" v-model="specImage" title="选择规格图片"></sc-upload-multiple>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="specImageVisible = false">取消</el-button>
					<el-button @click="confirmSpecImage" type="primary">确定</el-button>
				</div>
			</template>
		</el-dialog>
		<el-table :data="data" :header-cell-style="{}">
			<el-table-column label="商品规格" align="center">
				<el-table-column
					v-for="(value, key) in specTableHeader"
					:key="key"
					:index="key"
					:label="value.label"
				>
					<template #default="scope">
						{{ getSpecText(scope.row, value.id) }}
					</template>
				</el-table-column>
			</el-table-column>
			<el-table-column align="center">
				<template #header>
					<div style="display: flex; justify-content: space-between">
						<el-popover
							v-model:visible="specBatch.visible"
							placement="top-start"
							trigger="manual"
							:width="210"
						>
							<div style="margin-bottom: 5px;">
								{{ specTexts[specBatch.type] }}：
								<el-input-number
									v-model="specBatch.value"
									controls-position="right"
									size="small"
									:precision="specBatch.type === 'stock' ? 0 : 2"
									:min="0"
								/>
							</div>

							<div style="text-align: right">
								<el-button
									@click="specBatch.visible = false"
									size="small"
									type="text"
									>取消</el-button
								>
								<el-button @click="batchTableSpec" type="primary" size="small"
									>确定</el-button
								>
							</div>

							<template #reference>
								<div>
									批量设置：
									<el-button
										@click="showBatchSpec('stock')"
										type="text"
										size="small"
										>库存</el-button
									>
									<el-button
										@click="showBatchSpec('market_price')"
										type="text"
										size="small"
										>市场价</el-button
									>
									<el-button
										@click="showBatchSpec('sell_price')"
										type="text"
										size="small"
										>销售价</el-button
									>
									<el-button
										@click="showBatchSpec('cost_price')"
										type="text"
										size="small"
										>成本价</el-button
									>
								</div>
							</template>
						</el-popover>

						<div style="display: flex">
							<el-tooltip placement="top" content="正数增加，负数减少">
								<i
									class="el-icon-warning-outline"
									style="margin-top: 9.5px; margin-right: 3px"
								></i>
							</el-tooltip>
							<el-popover
								v-model:visible="specCount.visible"
								placement="top-start"
								trigger="manual"
								:width="210"
							>
								<div style="margin-bottom: 5px;">
									{{ specTexts[specCount.type] }}：
									<el-input-number
										v-model="specCount.value"
										controls-position="right"
										size="small"
										:precision="specCount.type === 'price' ? 2 : 0"
									/>
								</div>
								<div style="text-align: right">
									<el-button
										@click="specCount.visible = false"
										size="small"
										type="default"
										>取消</el-button
									>
									<el-button @click="countTableSpec" type="primary" size="small"
										>确定</el-button
									>
								</div>

								<template #reference>
									<div class="cs-ml-10">
										批量加减：
										<el-button
											@click="showCountSpec('stock')"
											type="text"
											size="small"
											>库存</el-button
										>
										<el-button
											@click="showCountSpec('market_price')"
											type="text"
											size="small"
											>市场价</el-button
										>
										<el-button
											@click="showCountSpec('sell_price')"
											type="text"
											size="small"
											>销售价</el-button
										>
										<el-button
											@click="showCountSpec('cost_price')"
											type="text"
											size="small"
											>成本价</el-button
										>
									</div>
								</template>
							</el-popover>
						</div>
					</div>
				</template>

				<el-table-column label="图片" prop="thumb" width="43" align="center">
					<template #default="scope">
						<el-popover
							placement="top"
							trigger="hover"
							:hide-after="50"
							width="170px"
							:disabled="!scope.row.thumb"
						>
							<el-image
								:src="getCoverUrl(scope.row.thumb)"
								fit="cover"
								v-if="scope.row.thumb"
								style="height: 140px; width: 140px; border-radius: 2px"
							/>
							<template #reference>
								<el-avatar
									class="cs-cp spec-photo"
									shape="square"
									@click="setSpecImage(scope.$index, scope.row.thumb)"
									:src="getCoverUrl(scope.row.thumb)"
									:size="32"
								>
									<el-icon><el-icon-picture /></el-icon>
								</el-avatar>
							</template>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column label="库存" prop="stock" width="85">
					<template #default="scope">
						<el-input-number
							v-model="scope.row.stock"
							class="smini-input"
							:controls="false"
							size="small"
							:precision="0"
							:min="0"
							:max="99999999"
						/>
					</template>
				</el-table-column>
				<el-table-column label="市场价" prop="market_price" width="85">
					<template #default="scope">
						<el-input-number
							v-model="scope.row.market_price"
							class="smini-input"
							size="small"
							:ref="`span_table_${scope.$index}_market_price`"
							:controls="false"
							:precision="0"
							:min="0"
							:max="99999999"
						/>
					</template>
				</el-table-column>
				<el-table-column label="销售价" prop="sell_price" width="85">
					<template #default="scope">
						<el-input-number
							v-model="scope.row.sell_price"
							class="smini-input"
							size="small"
							:controls="false"
							:precision="2"
							:min="0"
							:max="99999999"
						/>
					</template>
				</el-table-column>
				<el-table-column label="成本价" prop="cost_price" width="85">
					<template #default="scope">
						<el-input-number
							v-model="scope.row.cost_price"
							class="smini-input"
							size="small"
							:controls="false"
							:precision="2"
							:min="0"
							:max="99999999"
						/>
					</template>
				</el-table-column>

				<el-table-column label="SKU" prop="goods_sku" width="150">
					<template #default="scope">
						<el-input
							v-model="scope.row.goods_sku"
							size="small"
							:ref="`span_table_${scope.$index}_goods_sku`"
							clearable
						/>
					</template>
				</el-table-column>
				<el-table-column label="启用" prop="is_open" width="43" align="center">
					<template #default="scope">
						<el-checkbox v-model="scope.row.is_open" />
					</template>
				</el-table-column>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>
export default {
	props: {
		skusData: {
			type: Array,
			default() {
				return [];
			}
		},
		optionsData: {
			type: Array,
			default() {
				return [];
			}
		},
		baseUrl: { type: String, default: "" }
	},

	data: () => ({
		data: [],
		// [
		//   {
		//     ids: '1-11_2-21',
		//     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":21,"v":"大"}],
		//     price: '',
		//     guide: '',
		//   },
		//   {
		//     ids: '1-11_2-22',
		//     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":22,"v":"小"}],
		//     price: '',
		//     guide: '',
		//   }
		// ]
		specTexts: {
			stock: "库存",
			market_price: "市场价",
			sell_price: "销售价",
			cost_price: "成本价"
		},
		specBatch: {
			visible: false,
			type: "",
			value: 0
		},
		specCount: {
			visible: false,
			type: "",
			value: 0
		},
		specImage: [],
		specImageKey: {},
		specImageVisible: false
	}),

	computed: {
		skusList() {
			/**
			 * output:
			 * [
			 *   {
			 *     ids: '1-11_2-21',
			 *     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":21,"v":"大"}],
			 *   },
			 *   {
			 *     ids: '1-11_2-22',
			 *     skus: [{"k_id":1,"k":"颜色","v_id":11,"v":"红色"},{"k_id":2,"k":"尺寸","v_id":22,"v":"小"}],
			 *   }
			 * ]
			 */
			return this.$TOOL.sku.flatten(this.skusData).map((item) => {
				return this.getDiffSku(item);
			});
		},
		specTableHeader() {
			return this.skusData.map((item) => ({
				id: item.id,
				label: item.value
			}));
		}
	},

	watch: {
		skusList: {
			deep: true,
			immediate: true,
			handler(newSkus, oldSkus) {
				if (!newSkus.length) return (this.data = []);
				if (!oldSkus || !oldSkus.length) return this.initData(newSkus);
				if (newSkus.length === oldSkus.length) {
					// 当规格名和规格值数量未发生变化，更新 skus 即可
					return (this.data = newSkus.map((item, index) => ({
						...this.data[index],
						...item
					})));
				}

				// 当规格名的数量发生了变化
				if (newSkus[0].skus.length !== oldSkus[0].skus.length) {
					return this.initData(newSkus);
				}

				const diffIds = this.diffIds(newSkus, oldSkus);
				if (newSkus.length > oldSkus.length) {
					// 当添加了规格值
					let data = [];
					newSkus.forEach((item) => {
						const sku = this.data.find((_item) => _item.ids === item.ids);
						if (sku) {
							data.push(sku);
						} else {
							data.push(this.getDiffSku(item));
						}
					});
					this.data = data;
				} else {
					// 当删除了规格值
					this.data = this.data.filter((_item) => !diffIds.includes(_item.ids));
				}
			}
		}
	},
	mounted() {
		this.initData();
	},
	methods: {
		getOptionDataOne(_item) {
			// eslint-disable-next-line camelcase
			let tmp_vid = _item.skus
				.map((item) => {
					return item.v_id;
				})
				.join("_");

			// console.log(tmp_vid);
			// console.log(this.optionsData);
			let tmp = this.optionsData.filter((item) => {
				return item.specs == tmp_vid;
			});
			if (tmp.length) {
				return tmp[0];
			} else {
				return [];
			}
		},
		getDiffSku(_item) {
			// 找到对应的 option 数据
			const tmp = Object.assign(_item, this.getOptionDataOne(_item));
			return {
				skus: tmp.skus,
				thumb: tmp.thumb || "",
				stock: tmp.stock || 9999,
				market_price: tmp.market_price || 0,
				sell_price: tmp.sell_price || 0,
				cost_price: tmp.cost_price || 0,
				goods_sku: tmp.goods_sku || "",
				is_open: tmp.is_open === undefined ? true : tmp.is_open,
				ids: tmp.skus.reduce(
					(total, prev, index) =>
						`${total}${prev.k_id}-${prev.v_id}${
							index === tmp.skus.length - 1 ? "" : "_"
						}`,
					""
				)
			};
		},
		getSpecText(_row, _kId) {
			const tmp = _row.skus.filter((item) => {
				// eslint-disable-next-line eqeqeq
				return _kId == item.k_id;
			});
			// console.log(_row)
			if (tmp.length) {
				return tmp[0].v;
			} else {
				return "";
			}
		},
		diffIds(skusList1, skusList2) {
			// 两个数据的 ids 进行相差
			skusList1 = skusList1.map((item) => item.ids);
			skusList2 = skusList2.map((item) => item.ids);
			return this.$TOOL.diffArary(skusList1, skusList2);
		},

		initData() {
			this.data = this.skusList;
		},
		batchTableSpec() {
			const data = this.data;
			for (let key in data) {
				if (Object.prototype.hasOwnProperty.call(data, key)) {
					data[key][this.specBatch.type] = this.specBatch.value;
				}
			}
			this.specBatch.visible = false;
		},
		showBatchSpec(_type) {
			this.specBatch.value = 0;
			this.specBatch.type = _type;
			this.specBatch.visible = true;
		},
		showCountSpec(_type) {
			this.specCount.visible = true;
			this.specCount.value = 0;
			this.specCount.type = _type;
		},
		countTableSpec() {
			const data = this.data;
			for (let key in data) {
				if (Object.prototype.hasOwnProperty.call(data, key)) {
					let total = data[key][this.specCount.type] + this.specCount.value;
					data[key][this.specCount.type] = total >= 0 ? total : 0;
				}
			}
			this.specCount.visible = false;
		},
		getInputData() {
			return this.data.map((_item) => {
				return {
					/*specs_key: _item.skus
						.map((ss) => {
							return ss.v_id;
						})
						.join("_"),*/
					specs: _item.skus.map((ss) => {
						return ss.v_id;
					}),
					title: _item.skus
						.map((ss) => {
							return ss.v;
						})
						.join(";"),
					thumb: _item.thumb || "",
					stock: _item.stock || 9999,
					market_price: _item.market_price || 0,
					sell_price: _item.sell_price || 0,
					cost_price: _item.cost_price || 0,
					goods_sku: _item.goods_sku || "",
					is_open: _item.is_open === undefined ? true : _item.is_open
				};
			});
		},
		getCoverUrl(_thumb) {
			if (!_thumb) {
				return "";
			} else {
				if (/(http|https):\/\/([\w.]+\/?)\S*/.test(_thumb)) {
					return _thumb;
				}
				return this.baseUrl + _thumb;
			}
			// return _thumb
		},
		setSpecImage(index, image) {
			this.specImage = image;
			this.specImageKey = index;
			this.specImageVisible = true;
		},
		// 完成规格图片编辑
		confirmSpecImage() {
			// let data = this.data[this.specImageKey];
			// this.$set(data, "thumb", this.specImage);
			this.data[this.specImageKey].thumb = this.specImage;
			this.specImageVisible = false;
		}
	}
};
</script>
